package com.eqdd.yiqidian.ui.gongneng.renshi.meeting;

import android.app.AlertDialog;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.RecyclerViewRefreshCustom;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.MeetingTypeBean;
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.utils.TimeUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;
import com.shizhefei.mvc.MVCCoolHelper;

import org.reactivestreams.Publisher;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import io.reactivex.Flowable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

public class MeetingTypeListActivity extends BaseActivity {
    private RecyclerViewRefreshCustom dataBinding;
    private SlimAdapterEx<MeetingTypeBean> slimAdapterEx;
    private MVCCoolHelper<List<MeetingTypeBean>> mvcHelper;
    private ModelRx2DataSource<MeetingTypeBean> dataSource;
    private int pageNum = 0;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_recyclerview_refresh);
        initTopTitleBar(View.VISIBLE, "会议类型");
        initTopRightText("新增", v -> {
            startActivityForResult(MeetingTypeAddActivity.class, null, Config.ADD);
        });
    }

    @SuppressWarnings("unchecked")
    @Override
    public void initData() {
        if (slimAdapterEx == null) {
            dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
            dataBinding.recyclerView.addItemDecoration(new DividerLineItemDecoration(this));
            slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_144, new SlimInjector<MeetingTypeBean>() {
                @Override
                public void onInject(MeetingTypeBean data, IViewInjector injector) {
                    String frequency;
                    if (1 == data.getFrequency()) {
                        frequency = "每月";
                    } else if (2 == data.getFrequency()) {
                        frequency = "每周";
                    } else if (3 == data.getFrequency()) {
                        frequency = "每天";
                    } else {
                        frequency = "一次";
                    }
                    injector.text(R.id.tv_type, data.getType())
                            .text(R.id.tv_purpose, data.getAim())
                            .text(R.id.tv_time, String.format(Locale.CHINA, "%s - %s[%s - %s]", TimeUtil.formatWebTime1(data.getStartTime())
                                    , TimeUtil.formatWebTime1(data.getEndTime()), frequency, data.getTimeInterval()))
                            .text(R.id.tv_place, data.getPlace());
                }
            }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
            ItemClickSupport.addTo(dataBinding.recyclerView)
                    .setOnItemClickListener((recyclerView, position, v) -> {
                        int id = slimAdapterEx.getDataItem(position).getId();
                        Bundle bundle = new Bundle();
                        bundle.putInt(Config.ID, id);
                        startActivityForResult(MeetingTypeInfoActivity.class, bundle, Config.UPDATE);
                    })
                    .setOnItemLongClickListener((recyclerView, position, v) -> {

                        new AlertDialog.Builder(MeetingTypeListActivity.this)
                                .setTitle("提示")
                                .setMessage("是否删除" + slimAdapterEx.getDataItem(position).getType() + "?")
                                .setNegativeButton("取消", (dialog, witch) -> {
                                    dialog.dismiss();
                                })
                                .setPositiveButton("确定", (dialog, witch) -> {
                                    dialog.dismiss();
                                    OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.MEETING_TYPE_DELETE)
                                            .params("userGuid", user.getGuid())
                                            .params("companyId", user.getCompanyId())
                                            .params("settingId", slimAdapterEx.getDataItem(position).getId())
                                            .execute(new DialogCallBack<HttpResult>(MeetingTypeListActivity.this) {
                                                @Override
                                                public void onSuccess(Response<HttpResult> response) {
                                                    HttpResult result = response.body();
                                                    if (result.getStatus() == 200) {
                                                        ToastUtil.showShort("删除成功");
                                                    }
                                                }
                                            });

                                })
                                .create()
                                .show();

                        return true;
                    });

            dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
                @Override
                public Flowable<List> loadSource(int page, Rx2DataSource.DoneActionRegister register) {
                    pageNum = page == 1 ? 0 : pageNum;
                    return OkGo.<HttpResult<List<MeetingTypeBean>>>post(HttpConfig.BASE_URL + HttpConfig.MEETING_TYPE_LIST)
                            .params("userGuid", user.getGuid())
                            .params("comid", user.getCompanyId())
                            .params("page", pageNum)
                            .converter(new JsonConverter<HttpResult<List<MeetingTypeBean>>>() {
                                @Override
                                public void test() {
                                    super.test();
                                }
                            }).adapt(new FlowableBody<HttpResult<List<MeetingTypeBean>>>())
                            .flatMap(new Function<HttpResult<List<MeetingTypeBean>>, Publisher<List<MeetingTypeBean>>>() {
                                @Override
                                public Publisher<List<MeetingTypeBean>> apply(@NonNull HttpResult<List<MeetingTypeBean>> noticeWraperResultBeanHttpResult) throws Exception {
                                    if (page == 1) {
                                        mvcHelper.setAutoLoadMore(true);
                                    }
                                    pageNum = noticeWraperResultBeanHttpResult.getPage();
                                    return Flowable.just(noticeWraperResultBeanHttpResult.getItems() == null ? new ArrayList() : noticeWraperResultBeanHttpResult.getItems());
                                }
                            });
                }
            }, 1000);
            mvcHelper = new MVCCoolHelper<>(dataBinding.coolRefreshView);
            mvcHelper.setDataSource(dataSource);
            mvcHelper.setAdapter(slimAdapterEx);
            mvcHelper.refresh();
        }
    }


    @Override
    public void setView() {


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == Config.UPDATE) {
            mvcHelper.refresh();
        }
        if (resultCode == RESULT_OK && requestCode == Config.ADD){
            mvcHelper.refresh();
        }
    }
}
